// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { score, nickname, avatarUrl, combo, level } = event

  console.log('=== 开始处理分数更新 ===')
  console.log('微信上下文:', wxContext)
  console.log('用户openid:', wxContext.OPENID)
  console.log('用户appid:', wxContext.APPID)
  console.log('提交分数:', score)
  console.log('用户昵称:', nickname)
  console.log('用户头像:', avatarUrl)
  console.log('连击数:', combo)
  console.log('等级:', level)

  // 检查openid是否有效
  if (!wxContext.OPENID) {
    console.error('❌ 用户未登录，openid为空！')
    return { 
      success: false, 
      error: '用户未登录',
      needLogin: true 
    }
  }

  try {
    // 查询用户是否已存在
    console.log('🔍 查询用户是否存在...')
    const userResult = await db.collection('scores').where({
      openid: wxContext.OPENID
    }).get()

    if (userResult.data.length > 0) {
      // 用户存在，检查是否需要更新最高分
      const currentUser = userResult.data[0]
      console.log('用户已存在，当前最高分:', currentUser.bestScore, '新分数:', score)
      
      // 检查是否需要更新用户信息
      const needUpdateUserInfo = 
        nickname && nickname !== currentUser.nickname || 
        avatarUrl && avatarUrl !== currentUser.avatarUrl;
      
      if (score > currentUser.bestScore) {
        // 更新最高分和用户信息
        console.log('更新最高分和用户信息...')
        const updateResult = await db.collection('scores').doc(currentUser._id).update({
          data: {
            bestScore: score,
            nickname: nickname || currentUser.nickname,
            avatarUrl: avatarUrl || currentUser.avatarUrl,
            lastScore: score,
            lastCombo: combo,
            lastLevel: level,
            updateTime: new Date()
          }
        })
        console.log('更新结果:', updateResult)
        return { 
          success: true, 
          isNewRecord: true, 
          bestScore: score,
          message: '更新成功'
        }
      } else if (needUpdateUserInfo) {
        // 分数未超过最高分，但需要更新用户信息
        console.log('更新用户信息...')
        const updateResult = await db.collection('scores').doc(currentUser._id).update({
          data: {
            nickname: nickname || currentUser.nickname,
            avatarUrl: avatarUrl || currentUser.avatarUrl,
            lastScore: score,
            lastCombo: combo,
            lastLevel: level,
            updateTime: new Date()
          }
        })
        console.log('用户信息更新结果:', updateResult)
        return { 
          success: true, 
          isNewRecord: false, 
          bestScore: currentUser.bestScore,
          message: '用户信息已更新'
        }
      } else {
        console.log('分数未超过最高分，且用户信息无变化')
        return { 
          success: true, 
          isNewRecord: false, 
          bestScore: currentUser.bestScore,
          message: '无需更新'
        }
      }
    } else {
      // 新用户，直接插入
      console.log('📝 === 新用户，准备插入数据 ===')
      const newData = {
        openid: wxContext.OPENID,
        bestScore: score,
        lastScore: score,
        lastCombo: combo,
        lastLevel: level,
        nickname: nickname || '匿名玩家',
        avatarUrl: avatarUrl || '',
        createTime: new Date(),
        updateTime: new Date()
      }
      console.log('📝 准备插入的数据:', JSON.stringify(newData, null, 2))
      
      const addResult = await db.collection('scores').add({
        data: newData
      })
      console.log('✅ 插入结果:', addResult)
      
      return { 
        success: true, 
        isNewRecord: true, 
        bestScore: score,
        message: '新用户数据插入成功',
        insertId: addResult._id
      }
    }
  } catch (error) {
    console.error('更新分数失败：', error)
    return { 
      success: false, 
      error: error.message, 
      stack: error.stack 
    }
  }
} 